const express = require("express");
const router = express.Router();
const mysql = require("mysql");
const fs = require("fs");
const path = require("path");
const env = {
  host: "111.231.22.97",
  user: "wangs-web",
  password: "HsTjw82zF7f6fjWY",
  database: "wangs-web", //数据库名字
};
const { url } = require("./path");
const { errs } = require("../notice/index");

const exposeURL = path.join(__dirname, "/file");
//暴露
router.use(express.static(exposeURL));
const fileURL = path.join(__dirname, "/file/");

//noticeID
const indexs = () => {
  let str = "";
  for (let i = 0; i < 10; i++) {
    let ind = Math.ceil(Math.random() * 10);
    str += ind + 1;
  }
  return str;
};

//过滤
const filters = (e) => {
  let objs = {};
  for (let keys in e) {
    if (e[keys] != "" && e[keys] != undefined && e[keys] != null) {
      objs[keys] = e[keys];
    }
  }
  return Object.keys(objs);
};

//首页查询
const dashboardNotice = (req, res) => {
  let sql = "select * from noticelist ORDER BY date DESC";
  let pools = mysql.createPool(env);
  pools.query(sql, (err, result) => {
    if (err) {
      res.status(500);
      res.send({
        code: 500,
        msg: "error",
      });
      return;
    }
    res.send({
      code: 200,
      msg: "success",
      data: result.slice(0, 10),
    });
  });
};
router.get("/dashboardNotice", (req, res) => {
  dashboardNotice(req, res);
});

//查询通知

const totals = (sql, arr) => {
  let nums;
  return new Promise((resolve, reject) => {
    let pools = mysql.createPool(env);
    pools.query(sql, arr, (err, result) => {
      if (err) throw err;
      resolve(result);
    });
  });
};

const allNotice = (req, res) => {
  let pageNo = Number(req.query["pageNo"]);
  let pageSize = Number(req.query["pageSize"]);
  let offset = (pageNo - 1) * pageSize;
  let arrs = filters(req.query);
  if (arrs.length == 2) {
    let pools = mysql.createPool(env);
    let sql = "select * from noticelist ORDER BY date DESC limit ?,? ";
    pools.query(sql, [offset, pageSize], (err, result) => {
      if (err) throw err;
      //查询总数
      let sqls = "select count(*) from noticelist";
      pools.query(sqls, (err, total) => {
        if (err) throw err;
        console.log(total[0]["count(*)"]);
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: result,
            total: total[0]["count(*)"],
          },
        });
      });
    });
  } else {
    let pools = mysql.createPool(env);
    let sql = "select * from noticelist  where ";
    let sqls = "select count(*) from noticelist where ";
    let arrk = [];
    arrs.forEach((ele, index) => {
      if (ele != "pageNo" && ele != "pageSize") {
        if (index != arrs.length - 1) {
          sql = sql + ` ${ele} = ? and `;
          sqls = sqls + ` ${ele} = ? and `;
          arrk.push(req.query[`${ele}`]);
        } else {
          sql = sql + ` ${ele} = ? ORDER BY date DESC limit ?,? `;
          sqls = sqls + ` ${ele} = ? `;
          arrk.push(req.query[`${ele}`], offset, pageSize);
        }
      }
    });
    pools.query(sql, arrk, async (err, result) => {
      if (err) throw err;
      const total = await totals(sqls, arrk);
      console.log(total[0]["count(*)"]);
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: result,
          total: total[0]["count(*)"],
        },
      });
    });
  }
};
router.get("/allNotice", (req, res) => {
  allNotice(req, res);
});

//修改通知状态 0通知已发出 1审核通过 2审核不同过
const updateNoticeStatus = (req, res) => {
  const targetId = req.body["id"];
  const status = req.body["status"];
  let sql = "update noticelist set status = ? where id = ?";
  let pools = mysql.createPool(env);
  pools.query(sql, [status, targetId], (err, result) => {
    if (err) throw err;
    if (result.affectedRows == 1) {
      res.send({
        code: 200,
        msg: "success",
      });
    } else {
      res.send({
        code: 500,
        msg: "error",
      });
    }
  });
};
router.post("/updateNoticeStatus", (req, res) => {
  updateNoticeStatus(req, res);
});

//删除
const deleteNotice = (req, res) => {
  let pools = mysql.createPool(env);
  let sql = "delete from noticelist where id = ?";
  pools.query(sql, [req.query.id], (err, result) => {
    if (err) throw err;
    if (result.affectedRows == 1) {
      res.send({
        code: 200,
        msg: "success",
      });
      return;
    }
    res.send(errs());
  });
};
router.get("/deleteNotice", (req, res) => {
  deleteNotice(req, res);
});

//新增通知
const postNotice = (req, res) => {
  console.log(req.body, "body");
  const { title, html, author, date } = req.body;
  let filename = "/ws" + new Date().getTime() + ".txt";
  let url = path.join(__dirname, `file/${filename}`);
  console.log(url, "url");
  fs.writeFile(url, html, "utf-8", (err) => {
    if (err) {
      res.status(500);
      console.log(err);
    } else {
      let sql = "insert into noticelist values(?,?,?,?,?,?)";
      const queryArr = [indexs(), title, author, date, filename, "0"];
      console.log(queryArr, "6666");
      let pools = mysql.createPool(env);
      pools.query(sql, queryArr, (err, result) => {
        if (err) throw err;
        if (result.affectedRows == 1) {
          res.send({
            code: 200,
            msg: "success",
          });
          return;
        }
        res.send(errs());
      });
    }
  });
};

router.post("/postNotice", (req, res) => {
  postNotice(req, res);
});

//修改通知

const updateNotice = (req, res) => {
  let { html, status, title, author, date, id, url } = req.body;
  let urls = path.join(__dirname, `file/${url}`);
  fs.writeFile(urls, html, "utf-8", (err) => {
    if (err) {
      res.status(500);
      console.log(err);
    } else {
      let queryArr = [status, title, author, date, id];
      let sql =
        "update noticelist set status=?,title=?,author=?,date=? where id =?";
      let pools = mysql.createPool(env);
      pools.query(sql, queryArr, (err, result) => {
        if (err) {
          res.status(500);
          console.log(err);
        } else {
          if (result.affectedRows >= 1) {
            res.send({
              code: 200,
              msg: "修改成功",
            });
          } else {
            res.send({
              code: 500,
              msg: "error",
            });
          }
        }
      });
    }
  });
};
router.post("/updateNotice", (req, res) => {
  updateNotice(req, res);
});

//修改通知时读取
const getSingNotice = (req, res) => {
  const { id } = req.body;
  let pools = mysql.createPool(env);
  let sql = "select * from noticelist where id = ?";
  pools.query(sql, [id], (err, resk) => {
    try {
      const urls = fileURL + resk[0].url.slice(1, resk[0].url.length);
      fs.readFile(urls, "utf-8", (err, data) => {
        if (err) {
          res.status(500);
          console.log(err, "error");
        }
        res.send({
          code: 200,
          msg: "success",
          data: {
            data: {
              html: data,
              title: resk[0].title,
              author: resk[0].author,
              status: resk[0].status,
              date: resk[0].date,
              id: resk[0].id,
              url: resk[0].url,
            },
          },
        });
      });
    } catch {
      res.status(500);
      console.log(err, "error");
    }
  });
};

router.post("/getSingNotice", (req, res) => {
  getSingNotice(req, res);
});

//首页读取通知

const getNoticeDetail = (req, res) => {
  let sql = "select * from noticelist where id = ?";
  let queryArr = [req.params.id];
  let pools = mysql.createPool(env);
  pools.query(sql, queryArr, (err, result) => {
    if (err) throw err;
    let url = path.join(__dirname, `file/${result[0].url}`);
    fs.readFile(url, "utf-8", (err, data) => {
      if (err) throw err;
      res.send({
        code: 200,
        msg: "success",
        data: {
          data: data,
        },
      });
    });
  });
};

router.get("/getNoticeDetail/:id", (req, res) => {
  getNoticeDetail(req, res);
});

module.exports = router;
